import {findTagById, deleteTag} from '@/server/database/repositories/tag'
import {deleteItemsByTagId} from '@/server/database/repositories/itemOperation'
import { NextResponse } from "next/server"
import type { NextRequest } from 'next/server'
import {tagGetZodFormData,z} from "@/shared/formDataSchema"
export async function GET(req: NextRequest,
  {params}: {params: {id: string}}) {
  try {
    const id = + params.id
    tagGetZodFormData.parse({id})
    const tag = await findTagById(id)
    if (!tag)
      return NextResponse.json( '无法找到标签', { status: 404} )
    return NextResponse.json({ resource: tag })
  }
  catch (error) {
    if (error instanceof z.ZodError) {
      const statusMessage = error.issues.map(issue => issue.message).join("; ");
      return NextResponse.json( statusMessage, { status: 400} )
    }
    return NextResponse.json( '服务器出错，删除账目失败！', { status: 500} )
  }
}
export async function DELETE(req: NextRequest, {params}: {params: {id: string}}) {
  try {
    const id = + params.id
    const searchParams = req.nextUrl.searchParams
    const with_items  = searchParams.get('with_items')
    tagGetZodFormData.parse({id})
    let count = 0
    if(with_items === 'true'){
      count = await deleteItemsByTagId(id)
    }
    await deleteTag(id)
    const msg = count>0 ? '已删除标签和对应账目！' : '已删除标签！'
    return NextResponse.json({ resource: {}, msg })
  }
  catch (error) {
    if (error instanceof z.ZodError) {
      const statusMessage = error.issues.map(issue => issue.message).join("; ");
      return NextResponse.json( statusMessage, { status: 400} )
    }
    return NextResponse.json( '服务器出错，删除账目失败！', { status: 500} )
  }
}